package com.heima.behavior.interceptor;


import com.heima.common.dto.User;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInterceptor implements HandlerInterceptor {
    //前置拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的userId
        String userId = request.getHeader("userId");
        String name = request.getHeader("name");
        //如果前端使用设备登录,userId传的是0
        if (!StringUtils.isEmpty(userId) && !userId.equals("0")) {
            User user = new User();
            user.setUserId(Integer.parseInt(userId));
            if (!StringUtils.isEmpty(name)) {
                user.setName(name);
            }
            //放入本地线程
            AppThreadLocalUtil.set(user);
        }


        return true;
    }
//后置拦截
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //释放本地线程
        AppThreadLocalUtil.remove();
    }
//页面渲染
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
